using Crux.Core.Data;
using Crux.Core.EFCore;
using Crux.Core.EFCore.Test;
using EFCoreSecondLevelCacheInterceptor;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Web;
using Xunit.DependencyInjection.Logging;

namespace Crux.Core.EFCore.Test;
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMemoryCache();
        services.AddLogging((builder) =>
        {
            // builder.AddNLogWeb();
            builder.AddXunitOutput();
            builder.AddConsole();
        });
        services.AddScoped<ServiceProviderInterceptor>();
        services.AddScoped<IUniqueIdentifierGenerator, UniqueIdentifierGenerator>();
        services.AddDbContextFactory<TestDbContext>((s, builder) =>
        {
            builder = builder.UseSqlite("Data Source=test.db");

            // builder = builder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);

            var memoryCache = s.GetService<IMemoryCache>();
            if (memoryCache is not null)
                builder.UseMemoryCache(memoryCache);

            var loggerFactory = s.GetService<ILoggerFactory>();
                builder.UseLoggerFactory(loggerFactory);

            var secondLevel = s.GetService<SecondLevelCacheInterceptor>();
            var interceptor = s.GetService<ServiceProviderInterceptor>();
            if (interceptor is not null)
                builder.AddInterceptors(interceptor, secondLevel);

            builder.UseApplicationServiceProvider(s);
        }, ServiceLifetime.Scoped);

        services.AddEFCore();
        services.AddEFSecondLevelCache(options =>
            options.UseMemoryCacheProvider().UseCacheKeyPrefix("EF_")
        // Please use the `CacheManager.Core` or `EasyCaching.Redis` for the Redis cache provider.
        );
    }
}